package libs.yzx.zaza.acts;

import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/8/23
 */
public class OKHttpActivity extends AppCompatActivity{

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        buildHttpClient();

        //get();
        //post();
        upFile();
    }

    private OkHttpClient client;

    private void buildHttpClient(){
            client = new OkHttpClient.Builder()
                    .addInterceptor(new Interceptor() {
                        public Response intercept(Chain chain) throws IOException {
                            Request request = chain.request();
                            Response response = chain.proceed(request);
                            return response;
                        }
                    })
                    .connectTimeout(4000, TimeUnit.MILLISECONDS)
                    .readTimeout(4000,TimeUnit.MILLISECONDS)
                    .writeTimeout(4000, TimeUnit.MILLISECONDS)
                    .build();
    }


    private void get(){
        /* 如果需要参数 , 在url后边拼接 :  ?a=aaa&b=bbb..... */
        Request request = new Request.Builder().url("http://192.168.10.117:8080/test").build();
        client.newCall(request).enqueue(new Callback() {
            public void onResponse(Call call, final Response response) throws IOException {
                final String result = response.body().string();
                final boolean ok = response.isSuccessful();
                runOnUiThread(new Runnable() {
                    public void run(){
                        Toast.makeText(OKHttpActivity.this, result, Toast.LENGTH_SHORT).show();
                    }
                });
            }
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(OKHttpActivity.this, "error", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    private void post(){
        FormBody.Builder builder = new FormBody.Builder();
        /* 添加两个参数 */
        builder.add("p","我勒个去").add("a","hello");
        FormBody body = builder.build();
        Request request = new Request.Builder().url("http://192.168.10.117:8080/test").post(body).build();

        /* 下边和get一样了 */
        client.newCall(request).enqueue(new Callback() {
            public void onResponse(Call call, Response response) throws IOException {
                final  String bodyStr = response.body().string();
                final boolean ok = response.isSuccessful();
                runOnUiThread(new Runnable() {
                    public void run() {
                        if(ok){
                            Toast.makeText(OKHttpActivity.this, bodyStr, Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(OKHttpActivity.this, "server error : " + bodyStr, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
            public void onFailure(Call call,final IOException e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(OKHttpActivity.this, "error : "+e.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    private void upFile(){
        /* 第一个要上传的file */
        File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.jpg");
        RequestBody fileBody1 = RequestBody.create(MediaType.parse("application/octet-stream") , file1);
        String file1Name = "testFile1.txt";

        /* 第二个要上传的文件,这里偷懒了,和file1用的一个图片 */
        File file2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.jpg");
        RequestBody fileBody2 = RequestBody.create(MediaType.parse("application/octet-stream") , file2);
        String file2Name = "testFile2.txt";


        /* form的分割线 */
        String boundary = "xx--------------------------------------------------------------xx";

        MultipartBody mBody = new MultipartBody.Builder(boundary).setType(MultipartBody.FORM)
                /* 上传一个普通的String参数 , key 叫 "p" */
                .addFormDataPart("p" , "你大爷666")
                /* 底下是上传了两个文件 */
                .addFormDataPart("file" , file1Name , fileBody1)
                .addFormDataPart("file" , file2Name , fileBody2)
                .build();

        /* 下边的就和post一样了 */
        Request request = new Request.Builder().url("http://192.168.10.117:8080/test").post(mBody).build();
        client.newCall(request).enqueue(new Callback() {
            public void onResponse(Call call, Response response) throws IOException {
                final  String bodyStr = response.body().string();
                final boolean ok = response.isSuccessful();
                runOnUiThread(new Runnable() {
                    public void run() {
                        if(ok){
                            Toast.makeText(OKHttpActivity.this, bodyStr, Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(OKHttpActivity.this, "server error : " + bodyStr, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
            public void onFailure(Call call, final IOException e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(OKHttpActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

}
